import { defineStore } from 'pinia';
import axios from '../utils/axios';

export const useOutfitStore = defineStore('outfit', {
  state: () => ({
    outfitsList: [],
    selectedOutfit: null,
    // 临时数组，用于存储多个对象数据
    tempStorageArray: [],
    loading: false,
    error: null,
    filters: {
      season: '',
      occasion: ''
    },
    pagination: {
      currentPage: 1,
      pageSize: 5, // 每次请求获取5条数据
      totalCount: 0
    },
    // 临时存储app实例
    tempAppInstance: null,
    // 临时开关，用于判断是否选择了分类
    isCategorySelected: false
  }),

  getters: {
    // 获取筛选后的搭配列表
    filteredOutfits: (state) => {
      return state.outfitsList.filter(outfit => {
        // 季节筛选（支持数组字段）
        if (state.filters.season && (!outfit.seasons || !outfit.seasons.includes(state.filters.season))) {
          return false;
        }

        // 场合筛选
        if (state.filters.occasion && (!outfit.occasions || !outfit.occasions.includes(state.filters.occasion))) {
          return false;
        }

        return true;
      });
    }
  },

  actions: {
    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
      this.pagination.currentPage = 1;
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        season: '',
        occasion: ''
      };
      this.pagination.currentPage = 1;
    },

    // 获取搭配列表
    async fetchOutfitsList() {
      try {
        this.loading = true;
        this.error = null;

        // 构建查询参数，确保与后端控制器参数完全匹配
        const params = {
          page: Math.max(1, this.pagination.currentPage),
          pageSize: Math.max(1, Math.min(100, this.pagination.pageSize))
        };

        // 只添加非空的过滤条件，与后端筛选逻辑保持一致
        if (this.filters.season && this.filters.season !== 'all') {
          params.season = this.filters.season;
        }

        // 针对occasions数组字段的过滤参数
        // 由于数据库中occasions是数组类型，需要确保后端能够正确处理包含查询
        if (this.filters.occasion && this.filters.occasion !== 'all') {
          // 将场合作为查询参数，后端需要实现$in或包含查询逻辑
          params.occasion = this.filters.occasion;
          // console.log(`传递场合过滤参数: ${this.filters.occasion}`);
        }

        // 调用后端API，路径与outfitRoutes.js中的路由配置一致
        // console.log('发送请求获取搭配列表:', { endpoint: '/outfits', params });
        const response = await axios.get('/outfits', { params });
        // console.log('获取搭配列表响应数据:', response.items);

        // 确保响应数据结构正确
        // 处理axios响应结构，获取items属性
        const responseData = response.items || {};
        // console.log('处理后的响应数据:', responseData);

        // 确保items是数组 - 直接使用后端返回的数据
        let items = [];
        // 处理不同可能的数据结构
        if (Array.isArray(responseData)) {
          items = responseData;
        } else if (Array.isArray(responseData.items)) {
          items = responseData.items;
        } else if (Array.isArray(responseData.outfitsList)) {
          items = responseData.outfitsList; // 可能的另一种响应结构
        }

        // console.log('处理后的搭配数据:', { itemsLength: items.length, page: this.pagination.currentPage });

        // 针对第一页，直接替换数据
        if (this.pagination.currentPage === 1) {
          // console.log('第一页数据，替换现有列表');
          this.outfitsList = items;
        } else {
          // 后续页，追加数据
          // console.log(`第${this.pagination.currentPage}页，追加${items.length}条数据到现有列表`);
          this.outfitsList = [...this.outfitsList, ...items];
        }

        // 更新总数据量
        const totalCount = response.total || 0;
        this.pagination.totalCount = totalCount;
        // console.log(`更新总数据量: ${totalCount}`);

        // 同步后端返回的分页信息
        if (responseData.page) {
          this.pagination.currentPage = responseData.page;
          // console.log(`同步后端返回的页码: ${responseData.page}`);
        }
        if (responseData.pageSize) {
          this.pagination.pageSize = responseData.pageSize;
          // console.log(`同步后端返回的页大小: ${responseData.pageSize}`);
        }

        // 返回数据结构，确保前端可以正确解析，同时添加兼容字段
        // console.log('返回数据:', { 
        //   items: this.outfitsList, 
        //   total: this.pagination.totalCount, 
        //   currentPage: this.pagination.currentPage 
        // });
        return {
          items: this.outfitsList,
          total: this.pagination.totalCount,
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          // 为了兼容前端之前的逻辑，同时返回outfitsList和totalCount
          outfitsList: this.outfitsList,
          totalCount: this.pagination.totalCount
        };
      } catch (error) {
        console.error('获取搭配列表失败:', error);
        console.error('错误详情:', error.response?.data);
        // 优先使用后端返回的错误信息
        this.error = error.response?.data?.message || '获取搭配列表失败';
        // 在错误情况下返回空数据结构
        return {
          items: [],
          total: 0,
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };
      } finally {
        this.loading = false;
      }
    },

    // 获取单个搭配详情
    async fetchOutfitDetail(id) {
      try {
        this.loading = true;
        this.error = null;

        // 调用后端API，路径与outfitRoutes.js中的路由配置一致
        const response = await axios.get(`/outfits/${id}`);


        // 确保获取到响应数据 - 直接使用后端返回的数据，不做处理
        const outfitData = response;

        // 更新选中的搭配
        this.selectedOutfit = outfitData;

        return outfitData;
      } catch (error) {
        // 优先使用后端返回的错误信息
        this.error = error.response?.data?.message || '获取搭配详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 创建搭配
    async createOutfit(outfitData) {
      try {
        this.loading = true;
        this.error = null;

        // 验证必要字段是否存在，与后端验证保持一致
        if (!outfitData || !outfitData.finalOutfitImage || !outfitData.canvasData) {
          throw new Error('搭配图片和画布数据为必填项');
        }

        // 构建请求数据，确保字段名称与后端模型一致
        const requestData = {
          description: outfitData.description || '',
          clothesIds: Array.isArray(outfitData.clothesIds) ? outfitData.clothesIds : [],
          seasons: Array.isArray(outfitData.seasons) ? outfitData.seasons : [],
          occasions: Array.isArray(outfitData.occasions) ? outfitData.occasions : [],
          outfitPhoto: outfitData.outfitPhoto || '',
          finalOutfitImage: outfitData.finalOutfitImage,
          outfitInfo: Array.isArray(outfitData.outfitInfo) ? outfitData.outfitInfo : [],
          canvasData: outfitData.canvasData
        };

        // 调用后端API，路径与outfitRoutes.js中的路由配置一致
        const response = await axios.post('/outfits', requestData);

        // 获取创建的搭配数据
        const createdOutfit = response.data || {};

        // 丰富搭配数据，转换为前端需要的格式
        // const enrichedOutfit = await enrichOutfitWithClothesDetails(createdOutfit);

        // 添加到本地列表的开头
        this.outfitsList.unshift(createdOutfit);

        return createdOutfit;
      } catch (error) {
        // 优先使用后端返回的错误信息
        this.error = error.response?.data?.message || error.message || '创建搭配失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新搭配
    async updateOutfit(id, outfitData) {
      try {
        this.loading = true;
        this.error = null;

        // 构建请求数据，只包含实际需要更新的字段
        // 与后端控制器的动态更新逻辑保持一致
        const requestData = {};

        // 只包含非undefined的字段，避免覆盖已有值
        if (outfitData.description !== undefined) requestData.description = outfitData.description;
        if (outfitData.clothesIds !== undefined) requestData.clothesIds = outfitData.clothesIds;
        if (outfitData.seasons !== undefined) requestData.seasons = outfitData.seasons;
        if (outfitData.occasions !== undefined) requestData.occasions = outfitData.occasions;
        if (outfitData.outfitPhoto !== undefined) requestData.outfitPhoto = outfitData.outfitPhoto;
        if (outfitData.finalOutfitImage !== undefined) requestData.finalOutfitImage = outfitData.finalOutfitImage;
        if (outfitData.outfitInfo !== undefined) requestData.outfitInfo = outfitData.outfitInfo;
        if (outfitData.canvasData !== undefined) requestData.canvasData = outfitData.canvasData;

        // 调用后端API，路径与outfitRoutes.js中的路由配置一致
        const response = await axios.put(`/outfits/${id}`, requestData);

        // 获取更新后的搭配数据
        const updatedOutfit = response.data || {};

        // 直接使用后端返回的数据，不做额外处理
        // const enrichedOutfit = await enrichOutfitWithClothesDetails(updatedOutfit);

        // 更新本地列表
        const index = this.outfitsList.findIndex(item => item._id === id);
        if (index !== -1) {
          this.outfitsList[index] = updatedOutfit;
        }

        // 更新当前选中的搭配
        if (this.selectedOutfit && this.selectedOutfit._id === id) {
          this.selectedOutfit = updatedOutfit;
        }

        return updatedOutfit;
      } catch (error) {
        // 优先使用后端返回的错误信息
        this.error = error.response?.data?.message || '更新搭配失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除搭配
    async deleteOutfit(id) {
      try {
        this.loading = true;
        this.error = null;

        // 调用后端API，路径与outfitRoutes.js中的路由配置一致
        await axios.delete(`/outfits/${id}`);

        // 从本地列表中移除
        this.outfitsList = this.outfitsList.filter(item => item._id !== id);

        // 清除选中状态
        if (this.selectedOutfit && this.selectedOutfit._id === id) {
          this.selectedOutfit = null;
        }

        return true;
      } catch (error) {
        // 优先使用后端返回的错误信息
        this.error = error.response?.data?.message || '删除搭配失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取推荐搭配
    async getRecommendedOutfits(limit = 5) {
      try {
        this.loading = true;
        this.error = null;

        // 构建请求参数，与后端控制器期望的参数一致
        // 注意：后端当前实现不使用weather和temperature参数，改为limit参数
        const response = await axios.get('/outfits/recommend', {
          params: {
            limit: parseInt(limit) || 5
          }
        });

        // 获取响应数据
        const responseData = response.data || {};
        // 确保items是数组
        const recommendedItems = Array.isArray(responseData.items) ? responseData.items : [];

        // 丰富每个推荐搭配的数据，转换为前端需要的格式
        const enrichedOutfitsPromises = recommendedItems.map(outfit =>
          enrichOutfitWithClothesDetails(outfit)
        );
        const enrichedOutfits = await Promise.all(enrichedOutfitsPromises);

        return enrichedOutfits;
      } catch (error) {
        // 优先使用后端返回的错误信息
        this.error = error.response?.data?.message || '获取推荐搭配失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    },

    // 获取临时存储数组
    getTempStorageArray() {
      return this.tempStorageArray;
    },

    // 向临时存储数组添加数据
    addToTempStorage(data) {
      console.log('添加到临时存储:', data);

      if (data) {
        const newItem = {
          width: data.width || 100,
          height: data.height || null,
          url: data.imageUrls[0],
          id: data._id,
          x: data.x || 0,
          y: data.y || 0,
        };
        // 使用展开运算符创建新数组，确保Pinia能够检测到变化并触发持久化
        this.tempStorageArray = [...this.tempStorageArray, newItem];
        console.log('更新后的临时存储数组:', this.tempStorageArray);
      }
    },

    // 清空临时存储数组
    clearTempStorageArray() {
      // 安全有效地清空数组，避免内存泄漏
      this.tempStorageArray = [];
    },

    // 根据id删除临时存储数组中的数据
    deleteTempOutfit(id) {
      console.log('删除临时存储项，ID:', id);
      // 使用filter创建新数组，确保Pinia能够检测到变化并触发持久化
      this.tempStorageArray = this.tempStorageArray.filter(item => item.id !== id);
      console.log('删除后的临时存储数组长度:', this.tempStorageArray.length);
    }

  },

  persist: {
    key: 'piniaStore',
    paths: ['tempStorageArray']
  }
});